package com.clz.appdesign.myapp.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Path;
import android.support.annotation.Nullable;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;


/**
 * @author chenliangzhi
 * @date 2018/5/23
 * @describe 轨迹 用quadto的方式(二阶贝塞尔曲线) 更平滑
 */

public class TraJectoryViewByQuadto extends View {
    private Path mPath = new Path();
    private float preX, preY;

    public TraJectoryViewByQuadto(Context context) {
        super(context);
    }

    public TraJectoryViewByQuadto(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
    }

    public TraJectoryViewByQuadto(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                mPath.moveTo(event.getX(), event.getY());
                preX = event.getX();
                preY = event.getY();
                return true;
            case MotionEvent.ACTION_MOVE:
                float endx = (preX + event.getX()) / 2;
                float endy = (preY + event.getY()) / 2;
                mPath.quadTo(preX, preY, endx, endy);
                preX = event.getX();
                preY = event.getY();
                invalidate();
                break;
            default:
                break;
        }
        return super.onTouchEvent(event);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        Paint paint = new Paint();
        paint.setStyle(Paint.Style.STROKE);
        paint.setColor(Color.GREEN);
        paint.setStrokeWidth(8);
        canvas.drawPath(mPath, paint);
    }

    public void reset() {
        mPath.reset();
        invalidate();
    }

}
